const createStore = (reducer) => {
  let state;
  let listeners = [];

  const getState = () => state;

  //action 只能对象 {type: 'add', payload: 100}
  const dispatch = (action) => {
    state = reducer(state, action);
    listeners.forEach((listener) => listener());
  };

  const subscribe = (listener) => {
    listeners.push(listener);

    return () => {
      listeners = listeners.filter((l) => l !== listener);
    };
  };

  //执行初始化操作
  dispatch({}); // 初始化 state

  return {
    getState,
    dispatch,
    subscribe,
  };
};

let store = createStore(
  (state=300, action) => {
  //回调函数(reducer 函数)执行时机: 当store对象在创建以及在更新状态时, 会自动执行
  switch(action.type){
    case 'add':
      return state + action.payload;
    case 'sub':
      return state - action.payload;
    case 'times':
      return state * action.payload;
    //default 非常关键, 一定要返回 state, 否则创建的初始值将变为 undefined
    default: 
      return state;
  }
}
)

// console.log(store.getState());
store.subscribe(
  () => {
  console.log('update');
}
)

//更新
store.dispatch({type: 'add', payload: 100});

console.log(store.getState());



